<template>
  <div class="resource-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon><User /></el-icon>
          资源管理
        </h1>
        <div class="header-actions">
          <el-button @click="exportResources">
            <el-icon><Download /></el-icon>
            导出资源
          </el-button>
          <el-button type="primary" @click="optimizeResources">
            <el-icon><Setting /></el-icon>
            资源优化
          </el-button>
        </div>
      </div>
    </div>

    <!-- 资源概览卡片 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon people">
                <el-icon><User /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">总人员</div>
                <div class="card-value">{{ resourceOverview.totalPeople }}</div>
                <div class="card-desc">可用: {{ resourceOverview.availablePeople }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon equipment">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">设备数量</div>
                <div class="card-value">{{ resourceOverview.totalEquipment }}</div>
                <div class="card-desc">空闲: {{ resourceOverview.idleEquipment }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon budget">
                <el-icon><Money /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">总预算</div>
                <div class="card-value">¥{{ formatMoney(resourceOverview.totalBudget) }}</div>
                <div class="card-desc">已用: {{ resourceOverview.budgetUsageRate }}%</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon utilization">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">资源利用率</div>
                <div class="card-value">{{ resourceOverview.utilizationRate }}%</div>
                <div class="card-desc">较上月 +5%</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 功能标签页 -->
    <el-card class="main-content">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 人员分配 -->
        <el-tab-pane label="人员分配" name="personnel">
          <div class="personnel-container">
            <div class="personnel-toolbar">
              <el-button type="primary" @click="addPersonnelAssignment">
                <el-icon><Plus /></el-icon>
                分配人员
              </el-button>
              <el-button @click="viewWorkload">
                <el-icon><DataAnalysis /></el-icon>
                工作负荷分析
              </el-button>
              <div class="toolbar-right">
                <el-select v-model="personnelFilter" placeholder="筛选部门" style="width: 150px">
                  <el-option label="全部" value="" />
                  <el-option label="开发部" value="development" />
                  <el-option label="测试部" value="testing" />
                  <el-option label="设计部" value="design" />
                  <el-option label="产品部" value="product" />
                </el-select>
                <el-input
                  v-model="personnelSearchText"
                  placeholder="搜索人员"
                  style="width: 200px"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
            </div>
            
            <el-table :data="filteredPersonnelData" border style="width: 100%">
              <el-table-column prop="name" label="姓名" width="120">
                <template #default="{ row }">
                  <div class="personnel-info">
                    <el-avatar :size="32" :src="row.avatar" />
                    <span>{{ row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="department" label="部门" width="100" />
              <el-table-column prop="position" label="职位" width="120" />
              <el-table-column prop="skills" label="技能" width="200">
                <template #default="{ row }">
                  <el-tag
                    v-for="skill in row.skills"
                    :key="skill"
                    size="small"
                    style="margin-right: 5px"
                  >
                    {{ skill }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="currentProject" label="当前项目" width="150" />
              <el-table-column prop="workload" label="工作负荷" width="120">
                <template #default="{ row }">
                  <el-progress
                    :percentage="row.workload"
                    :color="getWorkloadColor(row.workload)"
                    :stroke-width="8"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="availability" label="可用性" width="100">
                <template #default="{ row }">
                  <el-tag :type="getAvailabilityType(row.availability)" size="small">
                    {{ row.availability }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="hourlyRate" label="时薪(元)" width="100" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="assignToProject(row)">
                    分配项目
                  </el-button>
                  <el-button type="success" size="small" @click="viewSchedule(row)">
                    查看排期
                  </el-button>
                  <el-button size="small" @click="editPersonnel(row)">
                    编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 设备调度 -->
        <el-tab-pane label="设备调度" name="equipment">
          <div class="equipment-container">
            <div class="equipment-toolbar">
              <el-button type="primary" @click="addEquipmentSchedule">
                <el-icon><Plus /></el-icon>
                设备调度
              </el-button>
              <el-button @click="viewEquipmentUtilization">
                <el-icon><PieChart /></el-icon>
                利用率分析
              </el-button>
              <div class="toolbar-right">
                <el-select v-model="equipmentTypeFilter" placeholder="设备类型" style="width: 150px">
                  <el-option label="全部" value="" />
                  <el-option label="服务器" value="server" />
                  <el-option label="网络设备" value="network" />
                  <el-option label="测试设备" value="testing" />
                  <el-option label="办公设备" value="office" />
                </el-select>
                <el-select v-model="equipmentStatusFilter" placeholder="设备状态" style="width: 150px">
                  <el-option label="全部" value="" />
                  <el-option label="空闲" value="idle" />
                  <el-option label="使用中" value="in-use" />
                  <el-option label="维护中" value="maintenance" />
                </el-select>
              </div>
            </div>
            
            <el-table :data="filteredEquipmentData" border style="width: 100%">
              <el-table-column prop="name" label="设备名称" width="150" />
              <el-table-column prop="type" label="设备类型" width="100" />
              <el-table-column prop="model" label="型号" width="120" />
              <el-table-column prop="location" label="位置" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getEquipmentStatusType(row.status)" size="small">
                    {{ getEquipmentStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="currentUser" label="当前使用者" width="120" />
              <el-table-column prop="utilizationRate" label="利用率" width="120">
                <template #default="{ row }">
                  <el-progress
                    :percentage="row.utilizationRate"
                    :stroke-width="8"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="dailyCost" label="日租金(元)" width="100" />
              <el-table-column prop="nextMaintenance" label="下次维护" width="120" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    size="small"
                    @click="scheduleEquipment(row)"
                    :disabled="row.status === 'maintenance'"
                  >
                    调度
                  </el-button>
                  <el-button type="warning" size="small" @click="maintenanceEquipment(row)">
                    维护
                  </el-button>
                  <el-button size="small" @click="editEquipment(row)">
                    编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 预算管理 -->
        <el-tab-pane label="预算管理" name="budget">
          <div class="budget-container">
            <div class="budget-toolbar">
              <el-button type="primary" @click="addBudgetItem">
                <el-icon><Plus /></el-icon>
                添加预算项
              </el-button>
              <el-button @click="generateBudgetReport">
                <el-icon><Document /></el-icon>
                生成报告
              </el-button>
              <div class="toolbar-right">
                <el-date-picker
                  v-model="budgetDateRange"
                  type="monthrange"
                  range-separator="至"
                  start-placeholder="开始月份"
                  end-placeholder="结束月份"
                  style="width: 250px"
                />
              </div>
            </div>
            
            <!-- 预算概览图表 -->
            <div class="budget-charts">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>预算执行情况</span>
                    </template>
                    <div ref="budgetExecutionChart" style="height: 300px;"></div>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>预算分类占比</span>
                    </template>
                    <div ref="budgetCategoryChart" style="height: 300px;"></div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
            
            <!-- 预算明细表 -->
            <el-table :data="budgetData" border style="width: 100%; margin-top: 20px;">
              <el-table-column prop="category" label="预算类别" width="120" />
              <el-table-column prop="item" label="预算项目" width="150" />
              <el-table-column prop="plannedAmount" label="计划金额(元)" width="120">
                <template #default="{ row }">
                  ¥{{ formatMoney(row.plannedAmount) }}
                </template>
              </el-table-column>
              <el-table-column prop="actualAmount" label="实际支出(元)" width="120">
                <template #default="{ row }">
                  ¥{{ formatMoney(row.actualAmount) }}
                </template>
              </el-table-column>
              <el-table-column prop="variance" label="差异" width="100">
                <template #default="{ row }">
                  <span :class="getVarianceClass(row.variance)">
                    {{ row.variance > 0 ? '+' : '' }}{{ row.variance }}%
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="progress" label="执行进度" width="120">
                <template #default="{ row }">
                  <el-progress
                    :percentage="row.progress"
                    :color="getBudgetProgressColor(row.progress)"
                    :stroke-width="8"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="responsible" label="负责人" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getBudgetStatusType(row.status)" size="small">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="editBudgetItem(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteBudgetItem(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 资源日历 -->
        <el-tab-pane label="资源日历" name="calendar">
          <div class="calendar-container">
            <div class="calendar-toolbar">
              <el-radio-group v-model="calendarView" @change="updateCalendarView">
                <el-radio-button label="month">月视图</el-radio-button>
                <el-radio-button label="week">周视图</el-radio-button>
                <el-radio-button label="day">日视图</el-radio-button>
              </el-radio-group>
              <div class="toolbar-right">
                <el-button @click="prevPeriod">
                  <el-icon><ArrowLeft /></el-icon>
                  上一期
                </el-button>
                <el-button @click="nextPeriod">
                  下一期
                  <el-icon><ArrowRight /></el-icon>
                </el-button>
                <el-button @click="goToday">今天</el-button>
              </div>
            </div>
            
            <!-- 资源日历图表 -->
            <div ref="resourceCalendar" class="resource-calendar" style="height: 600px;"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 人员分配对话框 -->
    <el-dialog v-model="showPersonnelDialog" title="人员分配" width="600px">
      <el-form :model="currentPersonnelAssignment" ref="personnelForm" label-width="100px">
        <el-form-item label="选择人员" prop="personnelId">
          <el-select v-model="currentPersonnelAssignment.personnelId" style="width: 100%">
            <el-option
              v-for="person in availablePersonnel"
              :key="person.id"
              :label="person.name"
              :value="person.id"
            >
              <span>{{ person.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ person.department }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分配项目" prop="projectId">
          <el-select v-model="currentPersonnelAssignment.projectId" style="width: 100%">
            <el-option
              v-for="project in availableProjects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="currentPersonnelAssignment.role" style="width: 100%">
            <el-option label="项目经理" value="manager" />
            <el-option label="开发工程师" value="developer" />
            <el-option label="测试工程师" value="tester" />
            <el-option label="UI设计师" value="designer" />
            <el-option label="产品经理" value="product" />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="currentPersonnelAssignment.startDate"
                type="date"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="currentPersonnelAssignment.endDate"
                type="date"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="工作量" prop="workload">
          <el-slider
            v-model="currentPersonnelAssignment.workload"
            :min="10"
            :max="100"
            :step="10"
            show-stops
            show-input
          >
            <template #default="{ value }">
              {{ value }}%
            </template>
          </el-slider>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="currentPersonnelAssignment.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPersonnelDialog = false">取消</el-button>
        <el-button type="primary" @click="savePersonnelAssignment">确定</el-button>
      </template>
    </el-dialog>

    <!-- 设备调度对话框 -->
    <el-dialog v-model="showEquipmentDialog" title="设备调度" width="500px">
      <el-form :model="currentEquipmentSchedule" ref="equipmentForm" label-width="100px">
        <el-form-item label="设备名称">
          <el-input v-model="selectedEquipment.name" disabled />
        </el-form-item>
        <el-form-item label="调度项目" prop="projectId">
          <el-select v-model="currentEquipmentSchedule.projectId" style="width: 100%">
            <el-option
              v-for="project in availableProjects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="使用人员" prop="userId">
          <el-select v-model="currentEquipmentSchedule.userId" style="width: 100%">
            <el-option
              v-for="person in availablePersonnel"
              :key="person.id"
              :label="person.name"
              :value="person.id"
            />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="currentEquipmentSchedule.startTime"
                type="datetime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="currentEquipmentSchedule.endTime"
                type="datetime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="使用目的">
          <el-input
            v-model="currentEquipmentSchedule.purpose"
            type="textarea"
            :rows="2"
            placeholder="请输入使用目的"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEquipmentDialog = false">取消</el-button>
        <el-button type="primary" @click="saveEquipmentSchedule">确定</el-button>
      </template>
    </el-dialog>

    <!-- 预算项编辑对话框 -->
    <el-dialog v-model="showBudgetDialog" title="预算项管理" width="500px">
      <el-form :model="currentBudgetItem" ref="budgetForm" label-width="100px">
        <el-form-item label="预算类别" prop="category">
          <el-select v-model="currentBudgetItem.category" style="width: 100%">
            <el-option label="人力成本" value="personnel" />
            <el-option label="设备租赁" value="equipment" />
            <el-option label="软件许可" value="software" />
            <el-option label="差旅费用" value="travel" />
            <el-option label="其他费用" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="预算项目" prop="item">
          <el-input v-model="currentBudgetItem.item" placeholder="请输入预算项目名称" />
        </el-form-item>
        <el-form-item label="计划金额" prop="plannedAmount">
          <el-input-number
            v-model="currentBudgetItem.plannedAmount"
            :min="0"
            :precision="2"
            style="width: 100%"
          >
            <template #prefix>¥</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="负责人" prop="responsible">
          <el-select v-model="currentBudgetItem.responsible" style="width: 100%">
            <el-option
              v-for="person in availablePersonnel"
              :key="person.id"
              :label="person.name"
              :value="person.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="currentBudgetItem.notes"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBudgetDialog = false">取消</el-button>
        <el-button type="primary" @click="saveBudgetItem">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import {
  User,
  Download,
  Setting,
  Monitor,
  Money,
  TrendCharts,
  Plus,
  DataAnalysis,
  Search,
  PieChart,
  Document,
  ArrowLeft,
  ArrowRight
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const router = useRouter()

// 响应式数据
const activeTab = ref('personnel')
const personnelFilter = ref('')
const personnelSearchText = ref('')
const equipmentTypeFilter = ref('')
const equipmentStatusFilter = ref('')
const budgetDateRange = ref([])
const calendarView = ref('month')
const showPersonnelDialog = ref(false)
const showEquipmentDialog = ref(false)
const showBudgetDialog = ref(false)

// 图表引用
const budgetExecutionChart = ref(null)
const budgetCategoryChart = ref(null)
const resourceCalendar = ref(null)

// 表单引用
const personnelForm = ref(null)
const equipmentForm = ref(null)
const budgetForm = ref(null)

// 资源概览数据
const resourceOverview = reactive({
  totalPeople: 45,
  availablePeople: 12,
  totalEquipment: 28,
  idleEquipment: 8,
  totalBudget: 2500000,
  budgetUsageRate: 68,
  utilizationRate: 85
})

// 人员数据
const personnelData = ref([
  {
    id: 1,
    name: '张三',
    department: '开发部',
    position: '高级工程师',
    skills: ['Java', 'Spring', 'Vue'],
    currentProject: '新产品开发',
    workload: 85,
    availability: '忙碌',
    hourlyRate: 200,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  },
  {
    id: 2,
    name: '李四',
    department: '测试部',
    position: '测试工程师',
    skills: ['自动化测试', '性能测试'],
    currentProject: '质量保证',
    workload: 60,
    availability: '可用',
    hourlyRate: 150,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  },
  {
    id: 3,
    name: '王五',
    department: '设计部',
    position: 'UI设计师',
    skills: ['Figma', 'Sketch', 'Photoshop'],
    currentProject: '界面设计',
    workload: 70,
    availability: '可用',
    hourlyRate: 180,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  }
])

// 设备数据
const equipmentData = ref([
  {
    id: 1,
    name: '开发服务器-01',
    type: 'server',
    model: 'Dell PowerEdge R740',
    location: '机房A',
    status: 'in-use',
    currentUser: '张三',
    utilizationRate: 85,
    dailyCost: 500,
    nextMaintenance: '2024-03-15'
  },
  {
    id: 2,
    name: '测试服务器-01',
    type: 'server',
    model: 'HP ProLiant DL380',
    location: '机房B',
    status: 'idle',
    currentUser: '',
    utilizationRate: 0,
    dailyCost: 450,
    nextMaintenance: '2024-04-10'
  },
  {
    id: 3,
    name: '网络交换机-01',
    type: 'network',
    model: 'Cisco Catalyst 9300',
    location: '机房A',
    status: 'maintenance',
    currentUser: '',
    utilizationRate: 0,
    dailyCost: 200,
    nextMaintenance: '2024-02-28'
  }
])

// 预算数据
const budgetData = ref([
  {
    id: 1,
    category: '人力成本',
    item: '开发团队薪资',
    plannedAmount: 800000,
    actualAmount: 650000,
    variance: -18.75,
    progress: 81,
    responsible: '张三',
    status: '正常'
  },
  {
    id: 2,
    category: '设备租赁',
    item: '服务器租赁费',
    plannedAmount: 200000,
    actualAmount: 180000,
    variance: -10,
    progress: 90,
    responsible: '李四',
    status: '正常'
  },
  {
    id: 3,
    category: '软件许可',
    item: '开发工具许可',
    plannedAmount: 150000,
    actualAmount: 165000,
    variance: 10,
    progress: 110,
    responsible: '王五',
    status: '超支'
  }
])

// 可用项目列表
const availableProjects = ref([
  { id: 1, name: '新产品开发项目' },
  { id: 2, name: '系统升级项目' },
  { id: 3, name: '质量改进项目' }
])

// 当前编辑的数据
const currentPersonnelAssignment = reactive({
  personnelId: '',
  projectId: '',
  role: '',
  startDate: '',
  endDate: '',
  workload: 50,
  notes: ''
})

const currentEquipmentSchedule = reactive({
  equipmentId: '',
  projectId: '',
  userId: '',
  startTime: '',
  endTime: '',
  purpose: ''
})

const currentBudgetItem = reactive({
  id: null,
  category: '',
  item: '',
  plannedAmount: 0,
  responsible: '',
  notes: ''
})

const selectedEquipment = reactive({})

// 计算属性
const filteredPersonnelData = computed(() => {
  let filtered = personnelData.value
  
  if (personnelFilter.value) {
    filtered = filtered.filter(person => person.department === personnelFilter.value)
  }
  
  if (personnelSearchText.value) {
    filtered = filtered.filter(person => 
      person.name.toLowerCase().includes(personnelSearchText.value.toLowerCase())
    )
  }
  
  return filtered
})

const filteredEquipmentData = computed(() => {
  let filtered = equipmentData.value
  
  if (equipmentTypeFilter.value) {
    filtered = filtered.filter(equipment => equipment.type === equipmentTypeFilter.value)
  }
  
  if (equipmentStatusFilter.value) {
    filtered = filtered.filter(equipment => equipment.status === equipmentStatusFilter.value)
  }
  
  return filtered
})

const availablePersonnel = computed(() => {
  return personnelData.value.filter(person => person.availability === '可用')
})

// 方法
const formatMoney = (amount) => {
  return (amount / 10000).toFixed(1) + '万'
}

const getWorkloadColor = (workload) => {
  if (workload >= 90) return '#F56C6C'
  if (workload >= 70) return '#E6A23C'
  return '#67C23A'
}

const getAvailabilityType = (availability) => {
  const typeMap = {
    '可用': 'success',
    '忙碌': 'warning',
    '不可用': 'danger'
  }
  return typeMap[availability] || 'info'
}

const getEquipmentStatusType = (status) => {
  const typeMap = {
    'idle': 'success',
    'in-use': 'warning',
    'maintenance': 'danger'
  }
  return typeMap[status] || 'info'
}

const getEquipmentStatusText = (status) => {
  const textMap = {
    'idle': '空闲',
    'in-use': '使用中',
    'maintenance': '维护中'
  }
  return textMap[status] || status
}

const getVarianceClass = (variance) => {
  if (variance > 0) return 'text-danger'
  if (variance < 0) return 'text-success'
  return 'text-info'
}

const getBudgetProgressColor = (progress) => {
  if (progress > 100) return '#F56C6C'
  if (progress >= 80) return '#E6A23C'
  return '#67C23A'
}

const getBudgetStatusType = (status) => {
  const typeMap = {
    '正常': 'success',
    '预警': 'warning',
    '超支': 'danger'
  }
  return typeMap[status] || 'info'
}

const addPersonnelAssignment = () => {
  Object.assign(currentPersonnelAssignment, {
    personnelId: '',
    projectId: '',
    role: '',
    startDate: '',
    endDate: '',
    workload: 50,
    notes: ''
  })
  showPersonnelDialog.value = true
}

const assignToProject = (person) => {
  Object.assign(currentPersonnelAssignment, {
    personnelId: person.id,
    projectId: '',
    role: '',
    startDate: '',
    endDate: '',
    workload: 50,
    notes: ''
  })
  showPersonnelDialog.value = true
}

const viewSchedule = (person) => {
  ElMessage.info(`查看 ${person.name} 的排期安排`)
}

const editPersonnel = (person) => {
  ElMessage.info(`编辑 ${person.name} 的信息`)
}

const savePersonnelAssignment = async () => {
  try {
    // 这里应该调用API保存人员分配
    ElMessage.success('人员分配成功')
    showPersonnelDialog.value = false
  } catch (error) {
    ElMessage.error('分配失败')
  }
}

const addEquipmentSchedule = () => {
  ElMessage.info('请先选择要调度的设备')
}

const scheduleEquipment = (equipment) => {
  Object.assign(selectedEquipment, equipment)
  Object.assign(currentEquipmentSchedule, {
    equipmentId: equipment.id,
    projectId: '',
    userId: '',
    startTime: '',
    endTime: '',
    purpose: ''
  })
  showEquipmentDialog.value = true
}

const maintenanceEquipment = (equipment) => {
  ElMessage.info(`安排 ${equipment.name} 的维护计划`)
}

const editEquipment = (equipment) => {
  ElMessage.info(`编辑 ${equipment.name} 的信息`)
}

const saveEquipmentSchedule = async () => {
  try {
    // 这里应该调用API保存设备调度
    ElMessage.success('设备调度成功')
    showEquipmentDialog.value = false
  } catch (error) {
    ElMessage.error('调度失败')
  }
}

const addBudgetItem = () => {
  Object.assign(currentBudgetItem, {
    id: null,
    category: '',
    item: '',
    plannedAmount: 0,
    responsible: '',
    notes: ''
  })
  showBudgetDialog.value = true
}

const editBudgetItem = (item) => {
  Object.assign(currentBudgetItem, { ...item })
  showBudgetDialog.value = true
}

const deleteBudgetItem = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定删除预算项 "${item.item}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = budgetData.value.findIndex(b => b.id === item.id)
    if (index > -1) {
      budgetData.value.splice(index, 1)
      ElMessage.success('预算项删除成功')
    }
  } catch (error) {
    // 用户取消删除
  }
}

const saveBudgetItem = async () => {
  try {
    if (currentBudgetItem.id) {
      // 编辑预算项
      const index = budgetData.value.findIndex(b => b.id === currentBudgetItem.id)
      if (index > -1) {
        Object.assign(budgetData.value[index], { ...currentBudgetItem })
      }
      ElMessage.success('预算项更新成功')
    } else {
      // 新增预算项
      const newItem = {
        ...currentBudgetItem,
        id: Date.now(),
        actualAmount: 0,
        variance: 0,
        progress: 0,
        status: '正常'
      }
      budgetData.value.push(newItem)
      ElMessage.success('预算项添加成功')
    }
    
    showBudgetDialog.value = false
    // 重新初始化图表
    nextTick(() => {
      initBudgetCharts()
    })
  } catch (error) {
    console.error('保存预算项失败:', error)
  }
}

const viewWorkload = () => {
  ElMessage.info('工作负荷分析功能开发中...')
}

const viewEquipmentUtilization = () => {
  ElMessage.info('设备利用率分析功能开发中...')
}

const generateBudgetReport = () => {
  ElMessage.info('生成预算报告功能开发中...')
}

const optimizeResources = () => {
  ElMessage.info('资源优化功能开发中...')
}

const exportResources = () => {
  ElMessage.info('导出资源功能开发中...')
}

const updateCalendarView = () => {
  nextTick(() => {
    initResourceCalendar()
  })
}

const prevPeriod = () => {
  ElMessage.info('上一期功能开发中...')
}

const nextPeriod = () => {
  ElMessage.info('下一期功能开发中...')
}

const goToday = () => {
  ElMessage.info('回到今天功能开发中...')
}

// 初始化预算图表
const initBudgetCharts = () => {
  // 预算执行情况图表
  if (budgetExecutionChart.value) {
    const executionChart = echarts.init(budgetExecutionChart.value)
    
    const executionOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['计划金额', '实际支出']
      },
      xAxis: {
        type: 'category',
        data: budgetData.value.map(item => item.item)
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}万'
        }
      },
      series: [
        {
          name: '计划金额',
          type: 'bar',
          data: budgetData.value.map(item => (item.plannedAmount / 10000).toFixed(1)),
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '实际支出',
          type: 'bar',
          data: budgetData.value.map(item => (item.actualAmount / 10000).toFixed(1)),
          itemStyle: {
            color: '#67C23A'
          }
        }
      ]
    }
    
    executionChart.setOption(executionOption)
  }
  
  // 预算分类占比图表
  if (budgetCategoryChart.value) {
    const categoryChart = echarts.init(budgetCategoryChart.value)
    
    const categoryData = budgetData.value.reduce((acc, item) => {
      if (!acc[item.category]) {
        acc[item.category] = 0
      }
      acc[item.category] += item.plannedAmount
      return acc
    }, {})
    
    const categoryOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: ¥{c}万 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '预算分类',
          type: 'pie',
          radius: '50%',
          data: Object.entries(categoryData).map(([name, value]) => ({
            name,
            value: (value / 10000).toFixed(1)
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    categoryChart.setOption(categoryOption)
  }
}

// 初始化资源日历
const initResourceCalendar = () => {
  if (!resourceCalendar.value) return
  
  const calendar = echarts.init(resourceCalendar.value)
  
  // 模拟资源日历数据
  const calendarData = []
  const startDate = new Date(2024, 1, 1)
  
  for (let i = 0; i < 30; i++) {
    const date = new Date(startDate.getTime() + i * 24 * 60 * 60 * 1000)
    calendarData.push([
      date.toISOString().split('T')[0],
      Math.floor(Math.random() * 100)
    ])
  }
  
  const calendarOption = {
    title: {
      text: '资源利用率日历',
      left: 'center'
    },
    tooltip: {
      formatter: function(params) {
        return `日期: ${params.value[0]}<br/>利用率: ${params.value[1]}%`
      }
    },
    visualMap: {
      min: 0,
      max: 100,
      type: 'piecewise',
      orient: 'horizontal',
      left: 'center',
      top: 65,
      pieces: [
        { min: 0, max: 30, color: '#67C23A' },
        { min: 30, max: 70, color: '#E6A23C' },
        { min: 70, max: 100, color: '#F56C6C' }
      ]
    },
    calendar: {
      top: 120,
      left: 30,
      right: 30,
      cellSize: ['auto', 13],
      range: '2024-02',
      itemStyle: {
        borderWidth: 0.5
      },
      yearLabel: { show: false }
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: calendarData
    }
  }
  
  calendar.setOption(calendarOption)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    calendar.resize()
  })
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initBudgetCharts()
    initResourceCalendar()
  })
})
</script>

<style scoped>
.resource-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.overview-card:hover {
  transform: translateY(-2px);
}

.card-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.card-icon.people {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.equipment {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.budget {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.utilization {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-desc {
  font-size: 12px;
  color: #909399;
}

.main-content {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.personnel-container,
.equipment-container,
.budget-container,
.calendar-container {
  padding: 20px;
}

.personnel-toolbar,
.equipment-toolbar,
.budget-toolbar,
.calendar-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.personnel-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.budget-charts {
  margin-bottom: 20px;
}

.resource-calendar {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.text-danger {
  color: #F56C6C;
}

.text-success {
  color: #67C23A;
}

.text-info {
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .resource-management {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .personnel-toolbar,
  .equipment-toolbar,
  .budget-toolbar,
  .calendar-toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .toolbar-right {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .budget-charts .el-col {
    margin-bottom: 20px;
  }
}
</style>